package com.lizhaoshan.controller;

import cn.hutool.core.util.StrUtil;
import com.lizhaoshan.common.OssTemplate;
import com.lizhaoshan.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Lu yuchao
 * @time 2022/5/1 0001 下午 11:57
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private OssTemplate ossTemplate;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        String contentType = file.getContentType();
        if (StrUtil.isEmpty(contentType)) {
            return Result.error("文件缺失");
        }

        //获取文件的后缀名和输入流
        String name = file.getContentType().split("/")[1];
        InputStream is = file.getInputStream();

        String urlAndName = ossTemplate.upload(name, is);

        return Result.success(urlAndName);
    }



    /**
     * 文件下载
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        try {
            //创建输入流，读取文件，下载
            FileInputStream inputStream = new FileInputStream(ossTemplate.getUrl() + "/" + name);
            //获取响应的输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //设置响应格式
            response.setContentType("image/jpeg");

            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            inputStream.close();
            outputStream.close();
            log.info("********文件下载");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
